//
//  YZLCarRedioPlayingViewController.m
//  Car
//
//  Created by dllo on 15/11/7.
//  Copyright © 2015年 岳明. All rights reserved.
//

#import "YZLCarRedioPlayingViewController.h"
#import <UIImageView+WebCache.h>
#import <AVFoundation/AVFoundation.h>
#import "YZLCarRedioPlayer.h"
#import "NSString+CZ.h"

@interface YZLCarRedioPlayingViewController ()<YZLCarRedioPlayerDelegate>

@property (nonatomic, strong) UIImageView *cycleImage;//旋转图
@property (nonatomic, strong) UILabel *periodsLabel;//期数
@property (nonatomic, strong) UILabel *titleLabel;//话题
@property (nonatomic, strong) UILabel *authorlabel;//主播
@property (nonatomic, strong) UILabel *guestLabel;//嘉宾
@property (nonatomic, strong) AVPlayer *player;//播放器
@property (nonatomic, assign) NSInteger redioNum;//索引
@property (nonatomic, strong) UIButton *button1;//播放
@property (nonatomic, strong) UISlider *slider;//进度条
@property (nonatomic, strong) UILabel *allTime;//总时间
@property (nonatomic, strong) UILabel *currentTimeLabel;//时间更新
@property (nonatomic, copy) NSString *redioUrlStr;

@end

@implementation YZLCarRedioPlayingViewController

//- (void)viewWillAppear:(BOOL)animated {
//    [super viewWillAppear:animated];
//    self.navigationController.navigationBarHidden = YES;
//}

#pragma mark - 创建旋转图
- (void)createImage {
    
    UIImageView *image = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"1-1.jpg"]];
    image.frame = CGRectMake(0, self.view.frame.size.height - 200 * self.view.frame.size.height / 667, self.view.frame.size.width, 200 * self.view.frame.size.height / 667);
    [self.view addSubview:image];

    
    // 磨砂(blur)效果
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 200 * self.view.frame.size.height / 667)];
    [imageView sd_setImageWithURL:[NSURL URLWithString:self.imageStr]];
    
    imageView.userInteractionEnabled = YES;

    UIVisualEffectView *visual = [[UIVisualEffectView alloc] initWithEffect:[UIBlurEffect effectWithStyle:UIBlurEffectStyleLight]];
    visual.frame = imageView.frame;
    visual.alpha = 0.95f;
    [imageView addSubview:visual];
    [self.view addSubview:imageView];
    
    //期数
    self.periodsLabel = [[UILabel alloc] initWithFrame:CGRectMake((self.view.frame.size.width - 120) / 2.f, 30, 120, 20)];
    [imageView addSubview:self.periodsLabel];
    self.periodsLabel.textColor = [UIColor whiteColor];
    self.periodsLabel.textAlignment = 1;
    self.periodsLabel.font = [UIFont systemFontOfSize:20];
    
    //旋转图
    self.cycleImage = [[UIImageView alloc] initWithFrame:CGRectMake(80, 60, (self.view.frame.size.width - 160), (self.view.frame.size.width - 160))];
//    self.cycleImage.center = imageView.center;
    [self.cycleImage sd_setImageWithURL:[NSURL URLWithString:self.imageStr]];
    self.cycleImage.layer.cornerRadius = (self.view.frame.size.width - 160) / 2.f;
    self.cycleImage.layer.masksToBounds = YES;
    [imageView addSubview:self.cycleImage];
    
    //话题
    self.titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(65, imageView.frame.size.height - (self.view.frame.size.width - 160) + 70, self.view.frame.size.width - 135, 20)];
    [imageView addSubview:self.titleLabel];
    self.titleLabel.textColor = [UIColor whiteColor];
    self.titleLabel.textAlignment = 1;

    //主播
    self.authorlabel = [[UILabel alloc] initWithFrame:CGRectMake(65, imageView.frame.size.height - (self.view.frame.size.width - 160) + 100, self.view.frame.size.width - 135, 20)];
    [imageView addSubview:self.authorlabel];
    self.authorlabel.textColor = [UIColor whiteColor];
    self.authorlabel.textAlignment = 1;

    //嘉宾
    self.guestLabel = [[UILabel alloc] initWithFrame:CGRectMake(65, imageView.frame.size.height - (self.view.frame.size.width - 160) + 130, self.view.frame.size.width - 135, 20)];
    [imageView addSubview:self.guestLabel];
    self.guestLabel.textColor = [UIColor whiteColor];
    self.guestLabel.textAlignment = 1;
    
    //播放
    self.button1 = [UIButton buttonWithType:UIButtonTypeCustom];
    self.button1.frame = CGRectMake((self.view.frame.size.width - 40) / 2.f, self.view.frame.size.height - 200 * self.view.frame.size.height / 667 + 60, 40, 40);
    [self.button1 setBackgroundImage:[UIImage imageNamed:@"bofang"] forState:UIControlStateNormal];
    [self.button1 setBackgroundImage:[UIImage imageNamed:@"zanting"] forState:UIControlStateSelected];
    [self.button1 addTarget:self action:@selector(play) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.button1];

    //上一首
    UIButton *button2 = [UIButton buttonWithType:UIButtonTypeCustom];
    button2.frame = CGRectMake((self.view.frame.size.width - 40) / 2.f - 80, self.view.frame.size.height - 200 * self.view.frame.size.height / 667 + 60, 40, 40);
    [button2 setBackgroundImage:[UIImage imageNamed:@"shangyishou"] forState:UIControlStateNormal];
    [button2 addTarget:self action:@selector(previous) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button2];

    //下一首
    UIButton *button3 = [UIButton buttonWithType:UIButtonTypeCustom];
    button3.frame = CGRectMake((self.view.frame.size.width - 40) / 2.f + 80, self.view.frame.size.height - 200 * self.view.frame.size.height / 667 + 60, 40, 40);
    [button3 setBackgroundImage:[UIImage imageNamed:@"xiayishou"] forState:UIControlStateNormal];
    [button3 addTarget:self action:@selector(next) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button3];

    //音乐总时间
    self.allTime = [[UILabel alloc] initWithFrame:CGRectMake(self.view.frame.size.width - 80, self.view.frame.size.height - 200 * self.view.frame.size.height / 667 + 20, 70, 20)];
    [self.view addSubview:self.allTime];
    self.allTime.textColor = [UIColor whiteColor];
    self.allTime.font = [UIFont systemFontOfSize:14];
    self.allTime.textAlignment = 1;
    self.allTime.text = @"00:00:00";
    
    //音乐播放时间
    self.currentTimeLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, self.view.frame.size.height - 200 * self.view.frame.size.height / 667 + 20, 70, 20)];
    [self.view addSubview:_currentTimeLabel];
    _currentTimeLabel.textColor = [UIColor whiteColor];
    _currentTimeLabel.font = [UIFont systemFontOfSize:14];
    _currentTimeLabel.textAlignment = 1;
    _currentTimeLabel.text = @"00:00:00";

    //音乐播放进度条
    self.slider = [[UISlider alloc] initWithFrame:CGRectMake(85, self.view.frame.size.height - 200 * self.view.frame.size.height / 667 + 20, self.view.frame.size.width - 170, 20)];
    [self.view addSubview:self.slider];
    [self.slider setThumbImage:[UIImage imageNamed:@"playbar_slider_thumb"] forState:UIControlStateNormal];
    
    //拖动进度条
    [self.slider addTarget:self action:@selector(slider:) forControlEvents:UIControlEventValueChanged];
    
    //返回
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(20, 25, 30, 30);
    [button setImage:[UIImage imageNamed:@"button"] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(returnButton1:) forControlEvents:UIControlEventTouchUpInside];
    [imageView addSubview:button];
    
}

//返回
- (void)returnButton1:(UIButton *)button {
    
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - 控件赋值
- (void)data:(YZLCarRedioListModel *)model {
    
    //期数
    self.periodsLabel.text = self.model.program_live_time;
    
    //话题
    if ([model.program_title isEqualToString:@""]) {
        self.titleLabel.text = @"话题: 未知";
    }else {
        self.titleLabel.text = [NSString stringWithFormat:@"话题: %@",model.program_title];
    }
    
    //主播
    if (model.anchor.count == 0) {
        self.authorlabel.text = @"主播: 未知";
    }else {
        
        if ([[model.anchor[0] objectForKey:@"username"] isEqualToString:@""]) {
            self.authorlabel.text = @"主播: 未知";
        }else {
            self.authorlabel.text = [NSString stringWithFormat:@"主播: %@", [model.anchor[0] objectForKey:@"username"]];
        }
    }
    
    //嘉宾
    if ([model.honoredguest isEqualToString:@""]) {
        self.guestLabel.text = @"嘉宾: 未知";
    }else {
        self.guestLabel.text = [NSString stringWithFormat:@"嘉宾: %@", model.honoredguest];
    }
    
    //音乐总时间
    self.allTime.text = model.program_time_length;
    
    //设置slider最大值

    //小时
    NSRange hourRange = {0, 2};
    NSInteger hour = [[model.program_time_length substringWithRange:hourRange] integerValue];
    //分钟
    NSRange minuteRange = {3, 2};
    NSInteger minute = [[model.program_time_length substringWithRange:minuteRange] integerValue];
    NSRange secondRange = {6, 2};
    //秒
    NSInteger second = [[model.program_time_length substringWithRange:secondRange] integerValue];
    self.slider.maximumValue = (float)(hour * 3600 + minute * 60 + second);

    //重置slider的值
    self.slider.value = 0;

    //重置currentLabel的值
    self.currentTimeLabel.text = @"00:00:00";
    
}

#pragma mark - YZLCarRedioPlayerDelegate  (时间监控)
- (void)AVPlayingWithProgress:(CGFloat)progress {

    //旋转图
    self.cycleImage.transform = CGAffineTransformRotate(self.cycleImage.transform, 0.01);

    //进度条进度
    self.slider.value = progress;
//    NSLog(@"~~~%f", self.slider.value);

    //开始时间
    self.currentTimeLabel.text = [NSString getMinuteSecondWithSecond:self.slider.value];
}

#pragma mark - 上一首/下一首/播放/暂停
//播放按钮
- (void)play {

    self.button1.selected = !self.button1.selected;
    if (self.button1.selected == YES) {

        [[YZLCarRedioPlayer shareInstance] play];

    }else {

        [[YZLCarRedioPlayer shareInstance] pause];
        
    }

}

//上一首按钮
- (void)previous {

    if (self.redioNum == 0) {
        self.redioNum = self.RedioArr.count - 1;
    }else {
        self.redioNum --;
    }
    self.model = self.RedioArr[self.redioNum];
    [self data:self.model];
    [[YZLCarRedioPlayer shareInstance] prepareToPlayWithStr:self.model.program_fileurl];
    //判断状态
    if (self.button1.selected == YES) {
        
        [[YZLCarRedioPlayer shareInstance] play];
    }
    //旋转图回复原来位置
    self.cycleImage.transform = CGAffineTransformIdentity;
    
    //通知中心
    NSString *indexPathStr = [NSString stringWithFormat:@"%ld", (long)self.redioNum];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"indexPath" object:nil userInfo:@{@"indexPath": indexPathStr}];
    
    //判断当前播放的曲目 存入本地
    self.redioUrlStr = self.model.program_fileurl;
    NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *filePath = [documentPath stringByAppendingPathComponent:@"redio.txt"];
    [self.redioUrlStr writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
}
//下一首按钮
- (void)next {
    if (self.redioNum == self.RedioArr.count - 1) {
        self.redioNum = 0;
    }else {

        self.redioNum ++;
    }
    self.model = self.RedioArr[self.redioNum];
    [self data:self.model];
    [[YZLCarRedioPlayer shareInstance] prepareToPlayWithStr:self.model.program_fileurl];
    //判断状态
    if (self.button1.selected == YES) {
        
        [[YZLCarRedioPlayer shareInstance] play];
    }
    //旋转图回复原来位置
    self.cycleImage.transform = CGAffineTransformIdentity;
    
    //通知中心
    NSString *indexPathStr = [NSString stringWithFormat:@"%ld", (long)self.redioNum];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"indexPath" object:nil userInfo:@{@"indexPath": indexPathStr}];
    
    //判断当前播放的曲目 存入本地
    self.redioUrlStr = self.model.program_fileurl;
    NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *filePath = [documentPath stringByAppendingPathComponent:@"redio.txt"];
    [self.redioUrlStr writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
}

#pragma mark -
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.view.backgroundColor = [UIColor clearColor];
    
    [self createImage];
    [self data:self.model];
    
    //bar颜色
    [self navigationbarColor];
    
    [[YZLCarRedioPlayer shareInstance] prepareToPlayWithStr:self.model.program_fileurl];
    [[YZLCarRedioPlayer shareInstance] play];
    
    //判断当前播放的曲目 存入本地
    self.redioUrlStr = self.model.program_fileurl;
    NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *filePath = [documentPath stringByAppendingPathComponent:@"redio.txt"];
    [self.redioUrlStr writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
    
    self.button1.selected = YES;
    [YZLCarRedioPlayer shareInstance].delegate = self;
    
    //注册通知  当前播放结束 自动跳到下一首
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(timeEnd) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
    
}

#pragma mark - 实现进度条拖动
- (void)slider:(UISlider *)slider {

    //播放器的进度
    [self seekToTime:slider.value];

    //currentTimeLabel的进度
    self.currentTimeLabel.text = [NSString getMinuteSecondWithSecond:slider.value];

}

//拖动进度条选择播放时间
- (void)seekToTime:(CGFloat)time
{
    // 先暂停
    [[YZLCarRedioPlayer shareInstance] pause];

    // 设置时间开始播放
    // value/timescale = seconds
    //参数1: 当前时间  每秒多少帧 CMTime
    [[YZLCarRedioPlayer shareInstance].player seekToTime:CMTimeMakeWithSeconds(time, [YZLCarRedioPlayer shareInstance].player.currentTime.timescale) completionHandler:^(BOOL finished) {

        if (finished) {
            if (self.button1.selected == YES) {
                [[YZLCarRedioPlayer shareInstance] play];
            }
        }
    }];
}

#pragma mark -  通知实现  (播放下一首)
- (void)timeEnd {

    [self next];
}


#pragma mark - 
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
